import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import el from 'element-ui/src/locale/lang/el'
import ca from 'element-ui/src/locale/lang/ca'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const token = 'TOKEN'

const whiteList = ['/login'] // no redirect whitelist 白名单，不需要权限

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  const hasGetUserInfo = store.getters.user // 获取保存在store中的用户信息
  // determine whether the user has logged in
  const hasToken = getToken(token)
  if (to.meta.auth) {
    // 需要权限才能进入的
    if (hasGetUserInfo) {
      next()
    } else if (hasToken) {
      // 验证有效性
      try {
        await store.dispatch('user/getInfo')
        next()
      } catch (e) {
        await store.dispatch('user/resetToken') // 删除原有的
        Message.error(e || '登录过期，请重新登录')
        next(`/login?redirect=${to.path}`) // 导航到登录页去
        NProgress.done()
      }
    } else {
      next(`/login?redirect=${to.path}`)
    }
  } else {
    if (to.path === '/login' && hasGetUserInfo) {
      next({ path: '/' })
      return
    }
    next()
  }
  NProgress.done()

  // 原本的鉴权流程
  // if (hasToken) {
  //   if (to.path === '/login') {
  //     // if is logged in, redirect to the home page
  //     next({ path: '/' })
  //     NProgress.done()
  //   } else {
  //     // 检查一下用户信息
  //     const hasGetUserInfo = store.getters.name
  //     if (hasGetUserInfo) {
  //       next()
  //     } else {
  //       // 没有用户信息时
  //       try {
  //         // 重新获取用户信息
  //         await store.dispatch('user/getInfo')
  //         next()
  //       } catch (e) {
  //         // 有问题时
  //         await store.dispatch('user/resetToken') // 删除原有的
  //         Message.error(e || 'Has Error')
  //         next(`/login?redirect=${to.path}`) // 导航到登录页去
  //         NProgress.done()
  //       }
  //     }
  //   }
  // } else {
  //   if (whiteList.indexOf(to.path) !== -1) {
  //     // in the free login whitelist, go directly
  //     next()
  //   } else {
  //     // other pages that do not have permission to access are redirected to the login page.
  //     next(`/login?redirect=${to.path}`)
  //     NProgress.done()
  //   }
  // }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
